<script lang="ts" setup>
import { useI18n } from 'vue-i18n';
import Tips from '../Tips/index.vue';
import { debounce, throttle } from 'lodash';
import { updateMaterialsQuantity } from '../../server/api/biz';
import { ElMessage } from 'element-plus';
import { computed } from 'vue';
const { t } = useI18n();
const emit = defineEmits([
  'allRowsData',
  'election-change',
  'elementInfoOPen',
  'getBomlist',
  'openprogressDialogVisible',
  'openSmtWaitingMailingModel',
  'openPcbWaitingMailingModel',
]);

const props = defineProps({
  // 表格数据
  data: {
    type: Array,
    required: true,
    default: () => [],
  },
  // 表格头
  columns: {
    type: Array,
    required: true,
    default: () => [],
  },
  loading: {
    type: Boolean,
    default: true,
  },
  // 斑马纹
  stripe: {
    type: Boolean,
    required: false,
    default: true,
  },

  // 是否显示序列号
  serial: {
    type: Boolean,
    default: false,
  },

  // 边框
  border: {
    type: Boolean,
    required: false,
    default: false,
  },

  // 表格对齐
  align: {
    type: String,
    required: false,
    default: 'left',
  },

  // 是否选中表格
  tableSelection: {
    type: Boolean,
    required: false,
    default: false,
  },
  // 单元格内容过长显示省略号
  tooltip: {
    type: Boolean,
    default: true,
  },

  // 表格高度
  tableHeight: {
    type: String,
    default: 'auto',
  },

  // 序号配置项
  serialOptions: {
    type: Object,
    default: () => {
      return {
        pageNum: 1,
        pageSize: 10,
      };
    },
  },
  mailingId: {
    type: String,
    default: '',
  },
  orderStatusObj: {
    type: Object,
    default: () => {
      return {};
    },
  },
  formatter: {
    type: Function,
    default: () => {},
  },
});

const mailStatus = {
  1: t('om.Tobemailed'),
  2: t('om.Inthemail'),
  3: t('om.Receivedgoods'),
  4: t('om.Cancel'),
};

const batch = {
  '-1': t('mall.unlimited'),
  '1': t('mall.one_year'),
  '2': t('mall.two_years'),
  '3': t('mall.three_years'),
};

const filterDataStyleShow = (type) => {
  const judgeTablePropType = {
    tag: 'inputSlot',
    btn: 'btnSlot',
    img: 'imgSlot',
  };

  return {
    type: type || false,
    name: judgeTablePropType[type],
  };
};
//   全选
function selectAllData<T>(val: T) {
  emit('allRowsData', val);
}
// 手动选择数据
function onSelectionChange<T>(row: T) {
  emit('election-change', row);
}
const smtLayerObj = computed(() => [
  {
    1: t('om.TopBottom'),
    2: t('om.Attic'),
    3: t('om.Bottom'),
  },
]);

/**
 * 打开邮寄信息单窗
 * @param row
 */
const openBom = (row) => {
  console.log(row);
  emit('elementInfoOPen', row);
};

const changeNum = (val: number, row) => {
  debouncedMethod(val, row.id);
};

/**
 * 防抖
 */
const debouncedMethod = debounce((value, id) => {
  // 例如，可以在输入框输入结束后触发此方法
  modifyMailingQuantity(value, id);
}, 500); // 设置延迟时间，单位为毫秒

/**
 * 修改邮寄数量
 * @param val
 * @param id
 */
const modifyMailingQuantity = (val: number, id) => {
  console.log(val, id);
  const obj = {
    expressMaterialsId: id,
    materialsQuantity: val,
  };
  updateMaterialsQuantity(obj).then((res) => {
    console.log(res);
    if (res.code === 200) {
      ElMessage.success(t('mall.modification_successful'));
      emit('getBomlist');
    }
  });
};

/**
 * 进度跟进
 */
const progressFollowUp = (row) => {
  emit('openprogressDialogVisible', row);
};

const smtWaitingMailing = (row) => {
  console.log(row);
  emit('openSmtWaitingMailingModel', row);
};

const pcbWaitingMailing = (row) => {
  console.log(row);
  emit('openPcbWaitingMailingModel', row);
};

// const loading = ref(true);
</script>
<template>
  <el-table
    :data="props.data"
    border
    class="table"
    style="width: 100%"
    @select-all="selectAllData"
    @selection-change="onSelectionChange"
  >
    <el-table-column v-if="props.tableSelection" type="selection" width="55" />
    <el-table-column
      v-if="props.serial"
      :label="t('coommon.index')"
      type="index"
      align="center"
      width="55"
    >
      <template #default="scope">
        <span>{{
          (props.serialOptions.pageNum - 1) * props.serialOptions.pageSize + scope.$index + 1
        }}</span>
      </template>
    </el-table-column>
    <el-table-column v-for="item of columns" :key="item.label" :prop="item.prop" v-bind="item">
      <!-- 单元格内容过长用hover显示内容框   -->
      <template #default="scope" v-if="item.label == $t('om.BOMBit')">
        <el-popover effect="light" trigger="hover" placement="top" width="`350px`">
          <template #default>
            <div>{{ scope.row.designator }}</div>
          </template>
          <template #reference>
            <div>{{ scope.row.designatorLength }}</div>
          </template>
        </el-popover>
      </template>

      <template #default="{ row }" v-if="item.label == $t('om.OrderInfo')">
        <div v-if="item.prop != 'pcbItems'">
          <span>
            {{ row.crmPcbaPcbOrder.productName }}, {{ row.crmPcbaPcbOrder.orderPcbNumber
            }}{{ $t('om.Chip') }}，{{ row.crmPcbaPcbOrder.pcbLength }}CM*{{
              row.crmPcbaPcbOrder.pcbWidth
            }}CM,{{
              smtLayerObj[0][
                item.prop == 'items' ? row.crmPcbaSmtOrder?.smtLayer : row.crmPcbaPcbOrder?.smtLayer
              ]
            }}
            <span v-if="row.crmPcbaPcbOrder.pcbLayer"
              >,{{ row.crmPcbaPcbOrder.pcbLayer }}{{ $t('om.Layer') }}</span
            >
          </span>
        </div>
        <div v-if="item.prop == 'pcbItems'">
          {{ row.crmPcbaPcbOrder.productName }}, {{ row.crmPcbaPcbOrder.orderPcbNumber
          }}{{ $t('om.Chip') }}

          <span v-if="row.crmPcbaPcbOrder.pcbLayer">
            {{ row.crmPcbaPcbOrder.pcbLayer }}{{ $t('om.Layer') }} </span
          >, {{ row.crmPcbaPcbOrder.pcbLength }}CM*{{ row.crmPcbaPcbOrder.pcbWidth }}CM
        </div>
      </template>

      <template #default="scope" v-if="item.label == $t('mall.shipping_information')">
        <div @click="openBom(scope.row)">
          <div class="color">
            {{ scope.row.crmPcbaSmtOrder?.totalMaterialsType || 0 }}{{ $t('mall.component_total')
            }}{{ scope.row.crmPcbaSmtOrder?.totalQuantiQty || 0 }}{{ $t('mall.item_count') }}
          </div>
          <div class="color">
            {{ scope.row.crmPcbaPcbOrder?.orderPcbNumber }}{{ $t('om.chippcb') }}
          </div>
        </div>
      </template>

      <template #default="scope" v-if="item.label == $t('om.Postal')">
        <div>
          <div v-if="scope.row.expressBomNumber" @click="smtWaitingMailing(scope.row)">
            <span class="color">{{ scope.row.expressBomNumber }}{{ $t('om.Component') }}</span>
            <span>{{ $t('om.Tobemailed') }}</span>
          </div>

          <div v-if="scope.row.expressPcbNumber" @click="pcbWaitingMailing(scope.row)">
            <span class="color">{{ scope.row.expressPcbNumber }}{{ $t('om.chippcb') }}</span>
            <span> {{ $t('om.Tobemailed') }}</span>
          </div>
        </div>
      </template>

      <template #default="scope" v-if="item.label == $t('om.OrderStatus')">
        <div>
          <div>{{ props.orderStatusObj[scope.row.orderStatus] }}</div>
          <div class="flxe" @click="progressFollowUp(scope.row)" v-if="item.prop != 'detail'">
            <img class="wh-16" src="../../assets/images/icons/time.png" alt="" />
            <span class="color">{{ $t('om.Progressfollowup') }}</span>
          </div>
        </div>
      </template>

      <template #default="scope" v-if="item.prop == 'payCurrencyTaxAmount'">
        <div>
          <div>{{ scope.row.symbol }}{{ scope.row.payCurrencyTaxAmount }}</div>
        </div>
      </template>

      <template #default="scope" v-if="item.label == $t('mall.component_information')">
        <div v-if="item.prop !== 'materialsName'">
          <div class="color" @click="openBom(scope.row)">
            {{ scope.row.materialsNumber || 0 }}{{ $t('mall.component_total')
            }}{{ scope.row.pcbNumber || 0 }}pcb
          </div>
        </div>
        <div class="mailing-components" v-if="item.prop == 'materialsName'">
          <div class="imgs">
            <img src="" alt="" />
          </div>
          <div>
            <ul>
              <li>IBE-ZY</li>
              <li>{{ $t('om.branding') }}：{{ scope.row.supplier }}</li>
              <li>{{ $t('om.OriginalModel') }}：{{ scope.row.supplierPn }}</li>
              <li>{{ $t('om.ComponentParameters') }}：{{ scope.row.description }}</li>
              <li>{{ $t('om.Batches') }}：{{ batch[scope.row.batchYearLimit] }}</li>
              <li>
                {{ $t('om.Datasheet') }}： <span class="color">{{ $t('om.Download') }}</span>
              </li>
            </ul>
          </div>
        </div>
      </template>

      <template #default="scope" v-if="item.label == $t('om.Statuses')">
        <div>
          <div>{{ mailStatus[scope.row.status] }}</div>
        </div>
      </template>

      <template #default="scope" v-if="item.label == $t('use.MailingComponents')">
        <div class="mailing-components" v-if="item.status !== 'toBeMailed'">
          <div class="imgs">
            <img src="" alt="" />
          </div>
          <div>
            <ul>
              <li>IBE-ZY</li>
              <li>{{ $t('om.branding') }}：{{ scope.row.bomVO?.supplier }}</li>
              <li>{{ $t('om.OriginalModel') }}：{{ scope.row.bomVO?.supplierPn }}</li>
              <li>
                {{ $t('om.ComponentParameters') }}：{{
                  scope.row.bomVO?.comments
                    ? scope.row.bomVO?.comments
                    : scope.row.bomVO?.description
                }}
              </li>
              <li>{{ $t('om.Batches') }}：{{ batch[scope.row.bomVO?.batchYearLimit] }}</li>
              <li>
                {{ $t('om.Datasheet') }}： <span class="color">{{ $t('om.Download') }}</span>
              </li>
            </ul>
          </div>
        </div>
        <div class="mailing-components" v-if="item.status == 'toBeMailed'">
          <div class="imgs">
            <img src="" alt="" />
          </div>
          <div>
            <ul>
              <li>IBE-ZY</li>
              <li>{{ $t('om.branding') }}：{{ scope.row.supplier }}</li>
              <li>{{ $t('om.OriginalModel') }}：{{ scope.row.supplierPn }}</li>
              <li>
                {{ $t('om.ComponentParameters') }}：{{
                  scope.row.comments ? scope.row.comments : scope.row.description
                }}
              </li>
              <li>{{ $t('om.Batches') }}：{{ batch[scope.row.batchYearLimit] }}</li>
              <li>
                {{ $t('om.Datasheet') }}： <span class="color">{{ $t('om.Download') }}</span>
              </li>
            </ul>
          </div>
        </div>
      </template>

      <template #default="scope" v-if="item.label == $t('om.MailingQuantity')">
        <div>
          <div v-if="item.prop == 'goMailingQuantity'">
            <div class="flxe">
              <el-input
                size="mini"
                :max="scope.row.materialsQuantity"
                min="1"
                @change="changeNum(scope.row.materialsQuantity, scope.row)"
                class="m-10"
                v-model="scope.row.materialsQuantity"
              />
              <Tips :content="$t('mall.quantity_exceeds_total')" />
            </div>
            <p>{{ $t('om.Minimummailingrequired') }}{{ scope.row.bomVO.totalQuantity }}</p>
          </div>
          <div v-if="item.prop == 'num'">
            {{ scope.row.materialsQuantity }}
          </div>
          <div v-if="item.prop === 'confirmMailing'">
            {{ scope.row.materialsQuantity }}
          </div>
          <div v-if="item.prop === 'orderPcbNumberPcb'">
            {{ scope.row.orderPcbNumber }}
          </div>
        </div>

        <p v-if="scope.row.pcbVO">
          {{ scope.row.pcbVO.orderPcbNumber }}
        </p>
      </template>

      <template #default="scope" v-if="item.label == $t('om.MailedPCBs')">
        <div>
          <ul class="flxe" v-if="item.prop == 'elementInfo'">
            <li>
              <p>{{ $t('om.GerberDocument') }}：{{ scope.row?.pcbVO?.fileVO.fileName }}</p>
              <p>{{ $t('om.Sheets') }}：{{ scope.row?.pcbVO?.productCategoryName }}</p>
              <p>
                {{ $t('om.BoardSize') }}：{{ scope.row?.pcbVO.pcbLength }}CM *
                {{ scope.row?.pcbVO.pcbWidth }} CM
              </p>
              <p>{{ $t('om.Platelayer') }}：{{ scope.row?.pcbVO.pcbLayer }}</p>
              <p>{{ $t('om.ofboards') }}：{{ scope.row.materialsQuantity }}</p>
            </li>
          </ul>

          <ul class="flxe" v-if="item.prop == 'waitingMailing'">
            <li>
              <p>
                {{ $t('om.GerberDocument') }}：{{
                  scope.row?.fileVO?.fileName || scope.row?.pcbVO?.fileVO.fileName
                }}
              </p>
              <p>
                {{ $t('om.Sheets') }}：{{
                  scope.row?.fileVO?.productCategoryName || scope.row?.pcbVO?.productCategoryName
                }}
              </p>
              <p>
                {{ $t('om.BoardSize') }}：{{
                  scope.row?.pcbLength || scope.row?.pcbVO?.pcbLength
                }}CM * {{ scope.row?.pcbWidth || scope.row?.pcbVO?.pcbWidth }} CM
              </p>
              <p>
                {{ $t('om.Platelayer') }}：{{ scope.row?.pcbLayer || scope.row?.pcbVO?.pcbLayer }}
              </p>
              <p>
                {{ $t('om.ofboards') }}：{{
                  scope.row?.orderPcbNumber || scope.row?.materialsQuantity
                }}
              </p>
            </li>
          </ul>

          <div v-if="item.prop == 'materialsNumber'">
            {{ scope.row.pcbNumber }}
          </div>
        </div>
      </template>

      <template #default="scope">
        <slot
          v-if="filterDataStyleShow(item.type).type"
          :name="filterDataStyleShow(item.type).name"
          :scope="scope"
        />
      </template>
    </el-table-column>
  </el-table>
</template>
<style scoped lang="scss">
.wh-16 {
  width: 16px;
  height: 16px;
  margin-right: 4px;
}
.m-top-8 {
  margin-top: 8px;
}
.table {
  width: 100%;
  height: 100%;
}
.color {
  color: #5255fe;
  cursor: pointer;
  text-align: center;
}
.color:hover {
  text-decoration: underline;
}
.mailing-components {
  display: flex;
}
.flxe {
  display: flex;
  align-items: center;
}
.m-10 {
  margin-right: 10px;
  margin-bottom: 8px;
}
.imgs {
  width: 90px;
  display: flex;
  align-items: center;
  justify-content: center;
  img {
    width: 72px;
    height: 72px;
    object-fit: cover;
  }
}
</style>
